package com.xunyin.modules.balance.rest;

import com.github.pagehelper.util.StringUtil;
import com.xunyin.annotation.AnonymousAccess;
import com.xunyin.api.XunyinException;
import com.xunyin.constant.Constants;
import com.xunyin.enums.BalanceSettingEnum;
import com.xunyin.enums.ErrorEnum;
import com.xunyin.enums.SettingTypeEnum;
import com.xunyin.enums.StatusEnum;
import com.xunyin.modules.balance.domain.MtSetting;
import com.xunyin.modules.balance.service.MtBalanceService;
import com.xunyin.modules.balance.service.MtSettingService;
import com.xunyin.modules.balance.service.dto.BalanceDto;
import com.xunyin.modules.balance.service.dto.RechargeRuleDto;
import com.xunyin.modules.mtuserbalance.service.MtUserBalanceService;
import com.xunyin.modules.security.security.TokenUtil;
import com.xunyin.modules.security.security.vo.JwtUser;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 余额管理controller
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@AllArgsConstructor
@Api(tags = "共享空间:余额管理")
@RestController
@RequestMapping("api/balance")
public class BackendBalanceController {

    private final MtSettingService mtSettingService;

    private final MtBalanceService balanceService;

    private final MtUserBalanceService mtUserBalanceService;
    private final TokenUtil tokenUtil;

    /**
     * 余额明细列表查询
     *
     * @param request HttpServletRequest对象
     * @return 余额明细列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> list(HttpServletRequest request) {

        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));
        String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
        String userId = request.getParameter("userId") == null ? "" : request.getParameter("userId");
        String orderSn = request.getParameter("orderSn") == null ? "" : request.getParameter("orderSn");
        String status = request.getParameter("status") == null ? StatusEnum.ENABLED.getKey() : request.getParameter("status");
        Integer storeId = (request.getParameter("storeId") == null || StringUtil.isEmpty(request.getParameter("storeId"))) ? 0 : Integer.parseInt(request.getParameter("storeId"));

        Map<String, Object> searchParams = new HashMap<>();
        if (StringUtil.isNotEmpty(mobile)) {
            searchParams.put("mobile", mobile);
        }
        if (StringUtil.isNotEmpty(userId)) {
            searchParams.put("userId", userId);
        }
        if (StringUtil.isNotEmpty(orderSn)) {
            searchParams.put("orderSn", orderSn);
        }
        if (StringUtil.isNotEmpty(status)) {
            searchParams.put("status", status);
        }
//        if (storeId > 0) {
//            searchParams.put("storeId", storeId);
//        }
        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        if (!user.getRoleIdList().contains(Long.valueOf(1L))) {
            searchParams.put("storeIdList", user.getStoreIdList());
        }
        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);
        paginationRequest.setSearchParams(searchParams);

        PaginationResponse<BalanceDto> paginationResponse = balanceService.queryBalanceListByPagination(paginationRequest);

        Map<String, Object> result = new HashMap<>();
        result.put("paginationResponse", paginationResponse);
        return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }

    /**
     * 充值设置详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> setting(HttpServletRequest request) {
        Integer storeId = (request.getParameter("storeId") == null || StringUtil.isEmpty(request.getParameter("storeId"))) ? 0 : Integer.parseInt(request.getParameter("storeId"));
        List<MtSetting> settingList = mtSettingService.getSettingList(SettingTypeEnum.BALANCE.getKey(), storeId);
        List<RechargeRuleDto> rechargeRuleList = new ArrayList<>();
        String remark = "";
        String status = "";
        if (settingList.size() > 0) {
            for (MtSetting setting : settingList) {
                if (setting.getName().equals(BalanceSettingEnum.RECHARGE_RULE.getKey())) {
                    status = setting.getStatus();
                    String item[] = setting.getValue().split(",");
                    if (item.length > 0) {
                        for (String value : item) {
                            String el[] = value.split("_");
                            if (el.length == 2) {
                                RechargeRuleDto e = new RechargeRuleDto();
                                e.setRechargeAmount(el[0]);
                                e.setGiveAmount(el[1]);
                                rechargeRuleList.add(e);
                            }
                        }
                    }
                } else if (setting.getName().equals(BalanceSettingEnum.RECHARGE_REMARK.getKey())) {
                    remark = setting.getValue();
                }
            }
        }

        Map<String, Object> result = new HashMap();
        result.put("rechargeRuleList", rechargeRuleList);
        result.put("remark", remark);
        result.put("status", status);
        return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }

    /**
     * 提交保存
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @RequestMapping(value = "/saveSetting", method = RequestMethod.POST)
    //@CrossOrigin
    public ResponseEntity saveSettingHandler(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        //String token = request.getHeader("Access-Token");
        String status = param.get("status") == null ? StatusEnum.ENABLED.getKey() : param.get("status").toString();
        String remark = param.get("remark") == null ? "" : param.get("remark").toString();
        Integer storeId = Integer.parseInt(param.get("storeId").toString());
        //Integer storeId = (request.getParameter("storeId") == null || StringUtil.isEmpty(request.getParameter("storeId"))) ? 0 : Integer.parseInt(request.getParameter("storeId"));
        List<LinkedHashMap> rechargeItems = (List) param.get("rechargeItem");
        if (rechargeItems.size() < 0) {
            //return getFailureResult(201, "充值规则设置不能为空");
            throw new XunyinException(ErrorEnum.E_100027.getErrorMsg());
        }

        String rechargeRule = "";
        for (LinkedHashMap item : rechargeItems) {
            if (rechargeRule.length() == 0) {
                rechargeRule = item.get("rechargeAmount").toString() + '_' + item.get("giveAmount").toString();
            } else {
                rechargeRule = rechargeRule + ',' + item.get("rechargeAmount").toString() + '_' + item.get("giveAmount").toString();
            }
        }

        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        if (!user.getRoleIdList().contains(Long.valueOf(1L)) && !user.getStoreIdList().contains(storeId)) {
            throw new XunyinException(ErrorEnum.E_100031.getErrorMsg());
        }

        MtSetting setting = new MtSetting();
        setting.setType(SettingTypeEnum.BALANCE.getKey());
        setting.setName(BalanceSettingEnum.RECHARGE_RULE.getKey());
        setting.setValue(rechargeRule);
        setting.setDescription(BalanceSettingEnum.RECHARGE_RULE.getValue());
        setting.setStatus(status);
        setting.setStoreId(storeId);
        //setting.setOperator(accountInfo.getAccountName());
        setting.setUpdateTime(new Date());
        mtSettingService.saveSetting(setting);

        // 保存充值说明
        MtSetting settingRemark = new MtSetting();
        settingRemark.setType(SettingTypeEnum.BALANCE.getKey());
        settingRemark.setName(BalanceSettingEnum.RECHARGE_REMARK.getKey());
        settingRemark.setValue(remark);
        settingRemark.setDescription("");
        settingRemark.setStatus(status);
        settingRemark.setStoreId(storeId);
        //settingRemark.setOperator(accountInfo.getAccountName());
        settingRemark.setUpdateTime(new Date());
        mtSettingService.saveSetting(settingRemark);
        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 获取用户充值统计数据
     * @return userBalanceStatDto
     */
    @GetMapping(value = "/data/getUserBalanceStat")
    @AnonymousAccess
    public ResponseEntity getUserBalanceStat(HttpServletRequest request,
                                            @RequestParam("storeId") Integer storeId,
                                            @RequestParam("mobile") String mobile) {
        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        String storeIds = "-1";
        if (!user.getRoleIdList().contains(Long.valueOf(1L))) {
            storeIds = StringUtils.join(user.getStoreIdList(), ",");
        }
        return new ResponseEntity<>(mtUserBalanceService.getUserBalanceStat(null, storeIds, mobile), HttpStatus.OK);

    }

}
